package com.yjs.app.trade.service.service.util.filter;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.yjs.app.trade.core.base.exception.BusinessException;
import com.yjs.app.trade.core.base.mybatis.dbutil.HandlerDataSource;
import com.yjs.app.trade.core.util.JedisUtil;
import com.yjs.app.trade.core.util.StringUtils;
import com.yjs.app.trade.entity.base.SysConstant;
import com.yjs.app.trade.service.service.util.TokenThreadLocal;

import net.sf.json.JSONObject;

/**
 * descrption: 使用AOP拦截特定的注解去动态的切换数据源
 */
@Aspect
@Component
@Order(1)
public class AuthorityFilterAop {
	
	public static String TOKEN = "TOKEN";
	
	public static String AUTHORITYTOKEN = "_AUTHORITY_TOKEN";
	
    //@within在类上设置
    //@annotation在方法上进行设置
    @Pointcut("@within(com.yjs.app.trade.service.service.util.filter.AuthorityFilterSource)||@annotation(com.yjs.app.trade.service.service.util.filter.AuthorityFilterSource)")
    public void pointcut() {}

    @SuppressWarnings("unchecked")
	@Before("pointcut()")
    public void doBefore(JoinPoint joinPoint)
    {
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        AuthorityFilterSource annotationClass = method.getAnnotation(AuthorityFilterSource.class);//获取方法上的注解
        if(annotationClass == null){
            annotationClass = joinPoint.getTarget().getClass().getAnnotation(AuthorityFilterSource.class);//获取类上面的注解
            if(annotationClass == null) {
            	return;
            }
        }
        //获取注解上的数据源的值的信息
        String dataSourceKey = annotationClass.permission();
        if (StringUtils.isNotBlank(dataSourceKey) && TokenThreadLocal.getValue(TOKEN) != null && 
        		JedisUtil.get(TokenThreadLocal.getValue(TOKEN).toString()) != null) {
        	JSONObject jsonObject = JSONObject.fromObject(JedisUtil.get(TokenThreadLocal.getValue(TOKEN).toString()));
        	List<Object> autList = jsonObject.getJSONArray("userPermissionId");
        	boolean flag = false;
        	for (Object object : autList) {
				if (StringUtils.equals(object.toString(), dataSourceKey)) {
					flag = true;
				} 
			}
        	if (!flag) {
        		throw new BusinessException(SysConstant.ErrorCode.NO_AUT, "没有权限");
        	}
        } else {
        	throw new BusinessException(SysConstant.ErrorCode.CODE_ERROR, "系统异常");
        }
    }

    @After("pointcut()")
    public void after(JoinPoint point) {
        //清理掉当前设置的数据源，让默认的数据源不受影响
        HandlerDataSource.clearDbType();
    }

}
